<!--
 * @Author: taosong 2289713738@qq.com
 * @Date: 2024-01-08 21:31:55
 * @LastEditors: taosong 2289713738@qq.com
 * @LastEditTime: 2024-01-10 22:16:21
 * @FilePath: \Song-ui\src\components\Collapse\Collapse.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div class="sg-collapse">
    <slot />
  </div>
</template>

<script lang="ts" setup>
import { ref, provide, watch } from 'vue'
import type { NameType, CollapsePorps, CollapseEmits } from './types'
import { collapseContentKey } from './types'
defineOptions({ name: 'SGCollapseItem' })
const props = defineProps<CollapsePorps>()
const emits = defineEmits<CollapseEmits>()

if (props.accordion && props.modelValue.length > 1) {
  console.warn('手风琴模式只能有一个子项')
}

watch(
  () => props.modelValue,
  (newVal) => {
    activeNames.value = newVal
  }
)

const activeNames = ref<NameType[]>(props.modelValue)

// item点击方法
const handleItemClick = (item: NameType) => {
  if (props.accordion) {
    // 手风琴模式
    activeNames.value = [activeNames.value[0] === item ? '' : item]
  } else {
    const index = activeNames.value.indexOf(item)
    if (index > -1) {
      // 存在,删除
      activeNames.value.splice(index, 1)
    } else {
      // 添加
      activeNames.value.push(item)
    }
  }

  emits('update:modelValue', activeNames.value)
  emits('change', activeNames.value)
}

provide(collapseContentKey, {
  activeNames,
  handleItemClick
})
</script>
